package zerotwo;

import java.util.PriorityQueue;

class Mytimertask implements Comparable<Mytimertask>{
    private long time;
    private Runnable task;
    public Mytimertask(Runnable task,long time){
        this.task=task;
        this.time=time;
    }
    public void run(){
        task.run();
    }
    public long gettime(){
        return time;
    }

    @Override
    public int compareTo(Mytimertask o) {
        return (int)(o.time-this.time);
    }
}
class Mytimer{
    PriorityQueue<Mytimertask> queue=new PriorityQueue<>();
    Object locker=new Object();
    public void schedule(Runnable task,long delay){
        synchronized(locker){
            Mytimertask task1=new Mytimertask(task,System.currentTimeMillis()+delay);
            queue.offer(task1);
            locker.notifyAll();
        }

    }
    public Mytimer(){
        Thread t=new Thread(()->{
                while(true){
                    synchronized (locker){
                        while(queue.isEmpty()){
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        Mytimertask task=queue.peek();
                        if(task.gettime()>System.currentTimeMillis()){
                            try {
                                locker.wait(task.gettime()-System.currentTimeMillis());
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }else{
                            task.run();
                            queue.poll();
                        }
                    }

                }


        });
        t.start();
    }
}



public class Test {
    public static void main(String[] args) {
        Mytimer mytimer=new Mytimer();
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        mytimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        System.out.println("hello main");

    }
}
